import time
from flask import Blueprint,request
from catch import redis_cli
from model.model import Order,House
from db_init import db
from tools.ali_pay import alipay
from tools.tools import my_router
from tools.tools import item2dict
from datetime import datetime
from flask_login import login_required
from flask import redirect

order = Blueprint('order',__name__)

# 订单接口
@order.route('/<int:o_id>',methods=['post'])
# 校验是否登录
@login_required
# @siwa.doc()
def add_order():
    order = request.json
    #拿到房屋id,接单人id，入住时间，退房时间
    db.session.add(Order(**order))
    db.session.commit()
    #订单创建数据
    return my_router(200)

# 获取所有的订单并且排序
@order.route('/house/')
def get_order():
    # 按时间倒序显示订单信息
    order = Order.query.all()
    order_list = item2dict(order)
    r = sorted(order_list,key=lambda x:x.get('start_time'))
    return my_router(200,r)

# 获取单个房子的所有订单并判断时间
@order.route('/house22/<int:h_id>',methods=['get'])
def get_one_house_order(h_id):
    house = Order.query.filter_by(house_id=h_id).all()
    time_1 = datetime.now().timestamp()
    with open('flask.log', 'ab') as f:
        if request.args.get('r'):
            f.write(f'loggr:ad_test {h_id} 这个房间报错了 广告页\n'.encode('utf-8'))
            # current_app.logger.info(f'loggr:ad_test {h_id} 这个房间报错了 广告页')
        else:
            f.write(f'loggr:ad_test {h_id} 这个房间报错了 原始页\n'.encode('utf-8'))
            # current_app.logger.info(f'loggr:ad_test {h_id} 这个房间报错了 原始页')
    list1 = []
    for i in house:
        if i.end_time > int(time_1):
            list1.append(item2dict(i))
    # 获取当前房子的订单
    # 今天以后
    return my_router(200,list1)

# 更新房子订单的状态
@order.route('/<int:o_id>',methods=['PUT'])
def put_house_order(o_id):
    # 拿到房东操作的一个字段
    stauts = request.json
    try:
        Order.query.filter_by(id=o_id).update(stauts)
    except Exception as e:
        print(e)
    db.session.commit()
    type = request.args.get('type')
    # 修改订单状态
    if type == "ali":
        return redirect('http://127.0.0.1:9527/order/')
    return my_router(200)

# 订单支付
# 微信支付用wechat
# start_t = time.time()
@order.route('/<int:order_id>/payment',methods=['get'])
def order_pay(order_id):
    # global start_t
    # new_t = time.time()
    # if new_t <= start_t + 1:
    #     time.sleep(start_t + 1 - new_t)
    # start_t = time.time()
    ali_ret = alipay.client_api(
        "alipay.trade.page.pay",
        biz_content={
            "out_trade_no": order_id,
            "total_amount": 1.1,
            "subject": "中文也没问题",
            "product_code": "FAST_INSTANT_TRADE_PAY",
        },
        return_url=f"http://127.0.0.1:9527/order/{order_id}?type=ali",  # this is optional
    )
    # return redirect('https://openapi-sandbox.dl.alipaydev.com/gateway.do?'+ali_ret)
    # 秦源的
    # return redirect('https://openapi.alipaydev.com/gateway.do?'+ali_ret)
    redis_cli.lpush('ali_order',str(order_id) + '/' + ali_ret)
    return str(time.time())

# @order.route('/<int:o_id>/ali_redis',methods=['get'])
# def order_pay_two(o_id):
#     while 1:
#         ret = redis_cli.blpop('ali_order')
#         print(ret)







